<!-- Login.vue -->
<template>
  <div class="login-container">
    <div class="background-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape shape-3"></div>
    </div>

    <el-card class="login-card">
      <div class="card-header-wrapper">
        <div class="user-icon">
          <svg viewBox="0 0 24 24" width="48" height="48">
            <path fill="currentColor"
              d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7L15 5.5V7H9V5.5L3 7V9L9 10.5V12L3 13.5V15.5L9 14V16L3 17.5V19.5L9 18V22H15V18L21 19.5V17.5L15 16V14L21 15.5V13.5L15 12V10.5L21 9Z" />
          </svg>
        </div>
        <h2 class="card-title">{{ isLogin ? '欢迎登录' : '创建账号' }}</h2>
        <p class="card-subtitle">{{ isLogin ? '请输入您的账号和密码' : '请填写注册信息' }}</p>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="0" class="login-form">
        <!-- 登录表单 -->
        <template v-if="isLogin">
          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <User />
                </el-icon>
              </span>
              <el-form-item prop="username" class="no-margin">
                <el-input v-model="form.username" placeholder="手机号或邮箱" size="large" class="custom-input" />
              </el-form-item>
            </div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Lock />
                </el-icon>
              </span>
              <el-form-item prop="password" class="no-margin">
                <el-input v-model="form.password" type="password" placeholder="登录密码" size="large" show-password
                  class="custom-input" @keyup.enter="handleSubmit" />
              </el-form-item>
            </div>
          </div>

          <!-- 验证码部分（只在登录时显示） -->
          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Key />
                </el-icon>
              </span>
              <el-form-item prop="captcha" class="no-margin">
                <el-input v-model="form.captcha" placeholder="图形验证码" size="large" class="custom-input captcha-input"
                  @keyup.enter="handleSubmit" />
              </el-form-item>
              <div class="captcha-wrapper" @click="refreshCaptcha">
                <div v-if="captchaSvg" class="captcha-image" v-html="captchaSvg"></div>
                <div v-else class="captcha-placeholder">点击刷新验证码</div>
              </div>
            </div>
          </div>
        </template>

        <!-- 注册表单 -->
        <template v-else>
          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Phone />
                </el-icon>
              </span>
              <el-form-item prop="phone" class="no-margin">
                <el-input v-model="form.phone" placeholder="手机号码" size="large" class="custom-input" />
              </el-form-item>
            </div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Message />
                </el-icon>
              </span>
              <el-form-item prop="email" class="no-margin">
                <el-input v-model="form.email" placeholder="邮箱地址" size="large" class="custom-input" />
              </el-form-item>
            </div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Lock />
                </el-icon>
              </span>
              <el-form-item prop="password" class="no-margin">
                <el-input v-model="form.password" type="password" placeholder="设置密码" size="large" show-password
                  class="custom-input" />
              </el-form-item>
            </div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <span class="input-icon">
                <el-icon>
                  <Lock />
                </el-icon>
              </span>
              <el-form-item prop="confirmPassword" class="no-margin">
                <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" size="large" show-password
                  class="custom-input" @keyup.enter="handleSubmit" />
              </el-form-item>
            </div>
          </div>
        </template>

        <el-form-item class="submit-item">
          <el-button type="primary" :loading="loading" @click="handleSubmit" class="submit-btn" size="large">
            <span v-if="!loading">{{ isLogin ? '立即登录' : '注册账号' }}</span>
            <span v-else>{{ isLogin ? '登录中...' : '注册中...' }}</span>
          </el-button>
        </el-form-item>
      </el-form>

      <div class="card-footer">
        <el-button type="text" @click="switchMode" class="switch-btn">
          {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
          <span class="switch-icon">→</span>
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sha1 } from 'js-sha1'
import {
  User,
  Lock,
  Phone,
  Message,
  Key
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { validateEmail, validatePassword, validatePhone } from '@/utils/validate'

const router = useRouter()
const userStore = useUserStore()

const isLogin = ref(true)
const loading = ref(false)
const formRef = ref()
const captchaSvg = ref('')
const captchaId = ref('')

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  captcha: '' // 新增验证码字段
})

// 修复验证规则 - 只在登录时验证验证码
const rules = computed(() => {
  const baseRules = {
    username: isLogin.value ? [
      { required: true, message: '请输入手机号或邮箱', trigger: 'blur' }
    ] : [],

    phone: !isLogin.value ? [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhoneRule, trigger: 'blur' }
    ] : [],

    email: !isLogin.value ? [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { validator: validateEmailRule, trigger: 'blur' }
    ] : [],

    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { validator: validatePasswordRule, trigger: 'blur' }
    ],

    confirmPassword: !isLogin.value ? [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' }
    ] : []
  }

  // 只在登录模式下验证验证码
  if (isLogin.value) {
    baseRules.captcha = [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { min: 4, max: 4, message: '验证码长度为4个字符', trigger: 'blur' }
    ]
  }

  return baseRules
})

// 自定义验证规则
const validatePhoneRule = (rule, value, callback) => {
  if (!validatePhone(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const validateEmailRule = (rule, value, callback) => {
  if (!validateEmail(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

const validatePasswordRule = (rule, value, callback) => {
  if (!validatePassword(value)) {
    callback(new Error('密码必须包含字母和数字,长度6-20位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const response = await userStore.getCaptchaAction()
    if (response.code === 0) {
      captchaSvg.value = response.data.captcha
      captchaId.value = response.data.captchaId
    }
  } catch (error) {
    ElMessage.error(error.message || '获取验证码失败')
  }
}

// 切换登录/注册模式
const switchMode = () => {
  isLogin.value = !isLogin.value
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  // 如果是切换到登录模式，获取验证码
  if (isLogin.value) {
    refreshCaptcha()
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 如果是注册模式，清除验证码的验证
    if (!isLogin.value) {
      formRef.value.clearValidate(['captcha'])
    }

    await formRef.value.validate()

    // 登录时需要验证码
    if (isLogin.value && !captchaId.value) {
      ElMessage.warning('请先获取验证码')
      await refreshCaptcha()
      return
    }

    loading.value = true

    if (isLogin.value) {
      // 登录（包含验证码）
      const response = await userStore.login({
        username: form.username,
        password: sha1(form.password),
        captcha: form.captcha,
        captchaId: captchaId.value
      })

      ElMessage.success(response.msg || '登录成功')
      router.push('/')

    } else {
      // 注册（不需要验证码）
      console.log(sha1(form.password));

      const response = await userStore.register({
        phone: form.phone,
        email: form.email,
        password: sha1(form.password)
        // 不传递验证码相关参数
      })

      ElMessage.success(response.msg || '注册成功')

      // 注册成功后自动切换到登录模式并填充账号
      form.username = form.email
      form.password = ''
      form.captcha = ''
      isLogin.value = true

      // 清空注册表单
      form.phone = ''
      form.email = ''
      form.confirmPassword = ''

      // 获取验证码
      await refreshCaptcha()

      if (formRef.value) {
        formRef.value.clearValidate()
      }

      ElMessage.info('请使用注册的邮箱或手机号登录')
    }
  } catch (error) {
    ElMessage.error(error.message || (isLogin.value ? '登录失败' : '注册失败'))
    // 登录失败时刷新验证码
    if (isLogin.value) {
      await refreshCaptcha()
      form.captcha = ''
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时如果是登录模式，获取验证码
onMounted(() => {
  if (isLogin.value) {
    refreshCaptcha()
  }
})
</script>

<style scoped>
/* 新增验证码相关样式 */
.captcha-input {
  flex: 1;
}

.captcha-wrapper {
  margin-left: 12px;
  width: 120px;
  height: 40px;
  border: 1px solid #fed7d7;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fff5f5;
  transition: all 0.3s ease;
}

.captcha-wrapper:hover {
  border-color: #ff6b6b;
  background: #ffeaea;
}

.captcha-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-placeholder {
  color: #a0aec0;
  font-size: 12px;
  text-align: center;
}

/* 调整输入框容器布局 */
.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

/* 原有样式保持不变 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/login-bg.png') no-repeat center center;
  background-size: cover;
  position: relative;
  overflow: hidden;
}

.background-shapes {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.shape {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 10%;
  left: 10%;
  transform: rotate(45deg);
}

.shape-2 {
  width: 80px;
  height: 80px;
  bottom: 20%;
  right: 10%;
  transform: rotate(30deg);
}

.shape-3 {
  width: 60px;
  height: 60px;
  top: 50%;
  left: 5%;
  transform: rotate(15deg);
}

.login-card {
  width: 440px;
  border-radius: 20px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.1);
  border: none;
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.card-header-wrapper {
  text-align: center;
  padding: 35px 0 25px;
}

.user-icon {
  color: #ff6b6b;
  margin-bottom: 16px;
}

.card-title {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 26px;
  font-weight: 600;
}

.card-subtitle {
  margin: 0;
  color: #718096;
  font-size: 14px;
}

.login-form {
  padding: 0 30px;
}

.form-group {
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 12px;
  z-index: 2;
  color: #a0aec0;
}

:deep(.custom-input .el-input__wrapper) {
  padding-left: 44px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #fed7d7;
  transition: all 0.3s ease;
}

:deep(.custom-input .el-input__wrapper:hover),
:deep(.custom-input .el-input__wrapper.is-focus) {
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.15);
  border-color: #ff6b6b;
}

.no-margin {
  margin-bottom: 0;
  width: 100%;
}

.submit-item {
  margin-bottom: 0;
}

.submit-btn {
  width: 100%;
  height: 50px;
  border-radius: 12px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  border: none;
  font-weight: 500;
  font-size: 16px;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.card-footer {
  padding: 25px 30px 30px;
  text-align: center;
  border-top: 1px solid #fed7d7;
}

.switch-btn {
  color: #718096;
  font-size: 14px;
  transition: color 0.3s ease;
}

.switch-btn:hover {
  color: #ff6b6b;
}

.switch-icon {
  margin-left: 4px;
  transition: transform 0.3s ease;
}

.switch-btn:hover .switch-icon {
  transform: translateX(2px);
}
</style>